package com.liycloud.auth.service;

import com.liycloud.common.core.constant.CacheConstants;
import com.liycloud.common.core.constant.SecurityConstants;
import com.liycloud.common.data.tenant.TenantContextHolder;


import org.springframework.cache.annotation.Cacheable;  // 缓存
import org.springframework.stereotype.Service;


import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;


import javax.sql.DataSource;

/**
 * @author lengleng
 * @date 2020/03/25
 * <p>
 * 扩展 JdbcClientDetailsService 支持多租户
 */
@Service
public class PigxClientDetailsServiceImpl extends JdbcClientDetailsService {

	public PigxClientDetailsServiceImpl(DataSource dataSource) {
		super(dataSource);
	}

	/**
	 * 重写原生方法支持redis缓存
	 * @param clientId
	 * @return ClientDetails
	 * @throws InvalidClientException
	 */
	@Override  // pigx_oauth:client:details
	@Cacheable(value = CacheConstants.CLIENT_DETAILS_KEY, key = "#clientId", unless = "#result == null")
	public ClientDetails loadClientByClientId(String clientId) {

		// 租户ID
		Integer tenantId = TenantContextHolder.getTenantId();

		// 更改默认 oauth_client_details 的切入口
		// 设置选择ClientDetail信息的sql
		super.setSelectClientDetailsSql(
				String.format( SecurityConstants.DEFAULT_SELECT_STATEMENT, tenantId)  // sys_oauth_client_details 默认的被切换
		);
		return super.loadClientByClientId(clientId);
	}

}
